package com.zdxlz.fcmp.common.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author: aman
 * @date 2025/2/11 13:42
 * @description
 */

@Configuration
@Slf4j
public class HttpClientThreadPoolConfig implements SmartLifecycle {
    private final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    private volatile boolean running = false;
    @Bean
    public TaskExecutor httpClientTaskExecutor() {

        // 设置核心线程数
        executor.setCorePoolSize(10);
        // 设置最大线程数
        executor.setMaxPoolSize(50);
        // 设置队列容量
        executor.setQueueCapacity(100);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("HttpClientExecutor-");
        // 当设置为 true 时，shutdown() 会阻塞，直到线程池中的所有任务（包括正在执行的任务）完成后才会返回
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置线程池关闭前等待所有任务完成的时间
        executor.setAwaitTerminationSeconds(60);
        // 初始化线程池
        executor.initialize();
        return executor;
    }

    @Override
    public void start() {
        log.info("【HttpClient】线程池启动...");
        running = true;
    }

    @Override
    public void stop() {
        log.info("【HttpClient】线程池关闭...");
        running = true;
    }

    @Override
    public boolean isRunning() {
        return running;
    }
}
